/** 角色申请 */

import React, {useEffect, useState} from 'react'
import {Button, Space, message} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {history, connect} from 'umi'
import {
	PlusOutlined,
	ArrowUpOutlined,
	ArrowDownOutlined,
} from '@ant-design/icons'
import moment from 'moment'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import Permissions from '@/components/Permissions'
import CustomModal from '@/components/Modal'
import {translateDataToTree} from '@/utils/common'
import {getCompany} from '@/service/common'
import CustomTable from '@/components/Table'
import BatchUpload from '@/components/BatchUpload'
import {modalApi} from '@/utils/modalReq'
import {downloadDocumentUrl} from '@/service/common/download'
import {
	deleteRole,
	getImportRoleApply,
	getRoleApplyList,
	getRoleErrorExcelList,
} from '@/service/system/roleApplication'

interface DataType {
	approvalUserStatus: any
	approvalStatus: number
	roleCode: number
	id: string
	roleName: string
	applyUser: string
	merchantId: string
	approvalTime: string
	applyTime: string
}

const formItemLayout = {
	labelCol: {flex: '120px'},
	wrapperCol: {flex: '1'},
}

const roleApplication = (props: any) => {
	const [dataSourse, setDataSourse] = useState<any[]>([])
	const [searchData, setSearchData] = useState({})
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [id, setId] = useState<string>('')
	const [companyData, setCompanyData] = useState([])
	const [loading, setLoading] = useState(false)
	const [total, setTotal] = useState()
	const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)
	const [formData, setFormData] = useState({})
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})

	/** 获取所属公司数据 */
	const onCompany = () => {
		getCompany({merchantId: props?.user?.orgId}).then((res: any) => {
			const list = translateDataToTree(res.data)
			setCompanyData(list as any)
		})
	}
	useEffect(() => {
		onCompany()
	}, [props?.user?.orgId])
	useEffect(() => {
		setFormData({
			startApplyTime: moment().subtract(1, 'months'),
			endApplyTime: moment(),
		})
	}, [])

	// 获取角色申请列表
	const getData = () => {
		setLoading(true)
		getRoleApplyList({
			...params,
			startApplyTime: moment()
				.subtract(1, 'months')
				.format('YYYY-MM-DD 00:00:00'),
			endApplyTime: moment().format('YYYY-MM-DD 23:59:59'),
			...searchData,
		})
			.then((res: any) => {
				if (res?.success) {
					setDataSourse(res?.data?.records)
					setTotal(res?.data?.total)
					setLoading(false)
				} else {
					setLoading(false)
				}
			})
			.catch((err) => {
				setDataSourse([])
				message.error(err)
				setLoading(false)
			})
	}
	useEffect(() => {
		getData()
	}, [params])

	/** 点击详情及编辑事件 */
	const onDetails = (type: string, record: DataType) => {
		history.push({
			pathname: `/system/roleApplication/${type}`,
			query: {
				id: record?.id,
			},
		})
	}

	const columns: ColumnsType<DataType> = [
		{
			title: '角色编码',
			dataIndex: 'roleCode',
			align: 'center',
			width: 120,
		},
		{
			title: '角色名称',
			dataIndex: 'roleName',
			align: 'center',
			width: 150,
		},
		{
			title: '状态',
			dataIndex: 'approvalStatus',
			align: 'center',
			width: 100,
			render: (text) => (
				<>{['待审核', '审核中', '审核通过', '审核拒绝'][text]}</>
			),
		},
		{
			title: '申请人',
			dataIndex: 'applyUser',
			align: 'center',
			width: 100,
		},
		{
			title: '申请时间',
			width: 180,
			dataIndex: 'applyTime',
			align: 'center',
		},
		{
			title: '审批人',
			width: 100,
			dataIndex: 'approvalUser',
			align: 'center',
		},
		{
			title: '审批时间',
			dataIndex: 'approvalTime',
			align: 'center',
			width: 180,
		},
		{
			title: '所属组织',
			dataIndex: 'merchantName',
			align: 'center',
			width: 200,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 120,
			render: (text: any, record) => (
				<Space size={12}>
					<Permissions permissionID="amc_system_permission_roleApplication_view">
						<Button
							type="link"
							onClick={() => {
								onDetails('view', record)
							}}>
							详情
						</Button>
					</Permissions>
					<Permissions permissionID="amc_system_permission_roleApplication_copy">
						<Button
							type="link"
							onClick={() => {
								onDetails('copy', record)
							}}>
							复制
						</Button>
					</Permissions>
					{record?.approvalStatus === 0 ||
					record?.approvalStatus === 3 ? (
						<>
							<Permissions permissionID="amc_system_permission_roleApplication_edit">
								<Button
									type="link"
									onClick={() => {
										onDetails('edit', record)
									}}>
									编辑
								</Button>
							</Permissions>
							<Permissions permissionID="amc_system_permission_roleApplication_delete">
								<Button
									type="link"
									onClick={() => {
										setId(record?.id)
										setIsModalOpen(true)
									}}>
									删除
								</Button>
							</Permissions>
						</>
					) : null}
					{record?.approvalUserStatus ? (
						<Permissions permissionID="amc_system_permission_roleApplication_examine">
							<Button
								type="link"
								onClick={() => {
									onDetails('examine', record)
								}}>
								审批
							</Button>
						</Permissions>
					) : (
						''
					)}
				</Space>
			),
		},
	]
	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					label: '申请角色',
					name: 'roleName',
					key: 'roleName',
					placeholder: '请输入角色编码或角色名称',
				},
				{
					type: 'select',
					key: 'approvalStatus',
					name: 'approvalStatus',
					label: '状态',
					keys: 'value',
					title: 'text',
					items: [
						{
							value: 0,
							text: '待审核',
						},
						{
							value: 1,
							text: '审核中',
						},
						{
							value: 2,
							text: '审核通过',
						},
						{
							value: 3,
							text: '审核拒绝',
						},
					],
				},
				{
					type: 'treeSelect',
					key: 'merchantId',
					name: 'merchantId',
					label: '所属组织',
					keys: 'id',
					title: 'name',
					treeData: companyData,
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'input',
					label: '申请人',
					name: 'applyUser',
					key: 'applyUser',
				},
				{
					type: 'time',
					subtype: 'date',
					label: '申请时间（起）',
					name: 'startApplyTime',
					key: 'startApplyTime',
				},
				{
					type: 'time',
					subtype: 'date',
					label: '申请时间（止）',
					name: 'endApplyTime',
					key: 'endApplyTime',
				},
			],
		},
		{
			type: 'group',
			key: 'group3',
			groupItems: [
				{
					type: 'input',
					label: '审批人',
					name: 'approvalUser',
					key: 'approvalUser',
				},
				{
					type: 'time',
					subtype: 'date',
					label: '审批时间（起）',
					name: 'startApprovalTime',
					key: 'startApprovalTime',
				},
				{
					type: 'time',
					subtype: 'date',
					label: '审批时间（止）',
					name: 'endApprovalTime',
					key: 'endApprovalTime',
				},
			],
		},
	]

	const onFinish = (values: any) => {
		const newValues = {
			...values,
			startApplyTime: values?.startApplyTime
				? moment(values?.startApplyTime).format('YYYY-MM-DD 00:00:00')
				: '',
			endApplyTime: values?.endApplyTime
				? moment(values?.endApplyTime).format('YYYY-MM-DD 23:59:59')
				: '',
			startApprovalTime: values?.startApprovalTime
				? moment(values?.startApprovalTime).format(
						'YYYY-MM-DD 00:00:00',
				  )
				: '',
			endApprovalTime: values?.endApprovalTime
				? moment(values?.endApprovalTime).format('YYYY-MM-DD 23:59:59')
				: '',
		}
		if (Object.keys(values)?.length === 3) {
			newValues.startApplyTime = moment()
				.subtract(1, 'months')
				.format('YYYY-MM-DD 00:00:00')
			newValues.endApplyTime = moment().format('YYYY-MM-DD 23:59:59')
		}
		setFormData(values)
		setSearchData(newValues)
		setParams({
			current: 1,
			size: 10,
		})
	}

	const onReset = () => {
		setSearchData({})
		setFormData({
			startApplyTime: moment().subtract(1, 'months'),
			endApplyTime: moment(),
		})
		setParams({
			current: 1,
			size: 10,
		})
	}

	const deleteData = () => {
		deleteRole(id)
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					setIsModalOpen(false)
					getData()
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}

	const errorColumns: ColumnsType<DataType> = [
		{
			title: '角色编码',
			dataIndex: 'roleCode',
			align: 'center',
			width: 120,
		},
		{
			title: '角色名称',
			dataIndex: 'roleName',
			align: 'center',
			width: 120,
		},
		{
			title: '所属组织',
			dataIndex: 'orgName',
			align: 'center',
			width: 150,
		},
		{
			title: '失败原因',
			dataIndex: 'reason',
			align: 'center',
			width: 200,
		},
	]

	return (
		<div className={styles.roleApplication}>
			<div className={styles.content}>
				<div className={styles.search}>
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formItems}
						formLayout={formItemLayout}
						values={formData}
					/>
				</div>
				<div className={styles.btnlist}>
					<Space size={12}>
						<Permissions permissionID="amc_system_permission_roleApplication_add">
							<Button
								icon={<PlusOutlined />}
								type="primary"
								ghost
								size="small"
								onClick={() => {
									history.push('/system/roleApplication/add')
								}}>
								新增数据
							</Button>
						</Permissions>
						<Permissions permissionID="amc_system_permission_roleApplication_import">
							<Button
								icon={<ArrowUpOutlined />}
								className={styles.warning}
								ghost
								size="small"
								onClick={() => {
									setIsUploadModalOpen(true)
								}}>
								导入
							</Button>
						</Permissions>
						<Permissions permissionID="amc_system_permission_roleApplication_export">
							<Button
								icon={<ArrowDownOutlined />}
								className={styles.import}
								ghost
								size="small"
								onClick={() => {
									downloadDocumentUrl({
										resourceId: '98',
										queryDesc: '角色申请导出,resourceId:98',
										queryParam: Object.keys(searchData)
											?.length
											? searchData
											: {
													startApplyTime: moment()
														.subtract(1, 'months')
														.format(
															'YYYY-MM-DD 00:00:00',
														),
													endApplyTime:
														moment().format(
															'YYYY-MM-DD 23:59:59',
														),
											  },
									})
								}}>
								导出
							</Button>
						</Permissions>
					</Space>
				</div>
				<CustomTable
					params={params}
					columns={columns}
					total={total}
					pagination
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={dataSourse}
				/>
			</div>
			<CustomModal
				text="确认要删除该数据吗？"
				onSubmit={deleteData}
				isModalOpen={isModalOpen}
				setIsModalOpen={setIsModalOpen}
			/>
			<BatchUpload
				isModalOpen={isUploadModalOpen}
				setIsModalOpen={setIsUploadModalOpen}
				importData={getImportRoleApply}
				onTableList={getRoleErrorExcelList}
				getListData={getData}
				downloadUrl="system/角色申请导入.xlsx"
				uploadFileUrl={`${modalApi.system}/roleApply/import/check`}
				columns={errorColumns}
				sourceId={48}
				templateType="角色申请导入"
			/>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(roleApplication)
